/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javamail.common;

import java.util.List;
import java.util.Vector;

/**
 *
 * @author sriram
 */
public class stringEncoder {
    public static String urlToText(String url) {
        if(url != null) {
            StringBuffer tmp = new StringBuffer();
            int i=0;
            try {
                while(true) {
                    char b = url.charAt(i++);
                    if(b == '+') {
                       tmp.append(' ');
                    }
                    else if(b == '%') {
                        char[] bArr = {url.toUpperCase().charAt(i++), url.toUpperCase().charAt(i++)};
                        int bu = 0, bt = 0;
                        if(bArr[1] >= 'A')
                            bu = (int) bArr[1] - '7';
                        else
                            bu = (int) bArr[1] - '0';
                        if(bArr[0] >= 'A')
                            bt = (int) bArr[0] - '7';
                        else
                            bt = (int) bArr[0] - '0';
                        int bInt = bt*16 + bu;
                        //System.out.print(bt);System.out.println(bu);
                        //System.out.println(bInt);
                        tmp.append((char) bInt);
                    }
                    else
                        tmp.append(b);
                }
            }
            catch (Exception e) {
                return tmp.toString();
            }
        }
        return null;
    }
    
    public static String txtToUrl(String txt) {
        if (txt!=null) {
            StringBuffer tmp = new StringBuffer();
            int i=0;
            try {
                while (true) {
                    int b = (int)txt.charAt(i++);
                    if(b<0x80) {
                        if(b == ' ')
                            tmp.append('+');
                        else
                            tmp.append((char)b);
                    }
                    else {
                        tmp.append("%");
                        if (b <= 0xf) tmp.append("0");
                        tmp.append(Integer.toHexString(b));
                    }
                }
            }
            catch (Exception e) {}
            return tmp.toString();
        }
        return null;
    }
}
